package com.ptmall.app.net.http;

import android.text.TextUtils;
import android.widget.Toast;

import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.ptmall.app.App;
import com.ptmall.app.bean.event.AccountError;
import com.ptmall.app.bean.event.Notice;
import com.ptmall.app.bean.model.ConfigBean;
import com.ptmall.app.utils.RxBus;
import com.ptmall.app.utils.SystemUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;


/**
 * @class describe
 * @anthor zyy mai:jingmengnihao@163.com
 * @time 2017/8/17 14:35
 * @change time
 * @class describe
 */
public class NetworkInterceptor implements Interceptor {
    private Gson mGson = new Gson();
    private static final String REDPACKET_LOST = "confirm_redpacket";
    private static final String WEB_STATUS = "web_status";//后台是否关闭状态判断

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        if (null != request || null != request.body()) {
            if (null != response) {
                String redPacketData = response.header(REDPACKET_LOST, "0");
                if ("1".equals(redPacketData)) {
                    RxBus.getInstance().post(new Notice(Notice.REDPACKET_LOST));
                }

                if (TextUtils.isEmpty(response.header(WEB_STATUS))) {//如果没有webstatus则判断后台关闭
                    //处理用户不存在的异常
                    SystemUtil.runOnUIThread(new Runnable(){
                        @Override
                        public void run() {
//                            Toast.makeText(App.getInstance().getApplicationContext(), "系统维护中", Toast.LENGTH_SHORT).show();
                        }
                    });
//                     RxBus.getInstance().post(new AccountError("提示", "系统维护中,点击退出App!", AccountError.ERROR_CODE_HOST_CLOSED));
                    //FloatViewHelper.showFloatView(App.getInstance().getApplicationContext());
                }
            }
            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            long end = System.currentTimeMillis();
            Buffer buffer = new Buffer();
//            if(!ErrorPush.canInsertXML){
//                return response;
//            }
            try {
                if(request==null||request.body()==null){
                    return response;
                }
                request.body().writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                String paramsStr = buffer.readString(charset);
                ConfigBean configBean = new ConfigBean();
                String url = request.url().toString();
                String method = url.substring(url.lastIndexOf("/") + 1, url.length());
                url = url.substring(0, url.lastIndexOf("/"));
                String model = url.substring(url.lastIndexOf("/") + 1, url.length());
                configBean.setMethod(method);
                configBean.setModel(model);
                configBean.setUse_time(tookMs + "");
                configBean.setHttp_status(response.code() + "");
                configBean.setInterface_param(mGson.toJson(paramsStr));
                String ss = end + "";
                ss = ss.substring(0, ss.length() - 3);
                configBean.setOccurr_time(ss);
                String txt = "请求地址:" + request.url()
                        + "\n请求参数:" + paramsStr
                        + "\n方法:" + model + "||" + method
                        + "\n返回结果:" + response.toString()
                        + "\n请求花费时间" + tookMs + "MS";
                LogUtil.d("xucc", txt);
            } catch (Exception e) {
                LogUtil.d("xucc", e.toString());
            }

        }
        return response;
    }

}
